<template>
	<my-modal v-if="isShow" :show="isShow" @close="closeModal" title="我的学习二维码" :showCancel="false" confirmText="保存图片"
		@confirm="saveQRCode">
		<view class="code-modal-content">
			<view class="uni-flex">
				<view class="modal-image-box uni-flex">
					<image :src="avatarUrl" class="modal-content-image" />
				</view>
				<view class="modal-user-info uni-flex uni-column">
					<view>{{userName}}</view>
					<view>时间：{{time}}</view>
				</view>
			</view>
			<view class="modal-qr-box uni-flex uni-column">
				<u-qrcode v-if="visible" :size="200" :text="signQrCode" ref="uQRCode" />
				<view class="modal-hint">请在社区、学堂、教室里出示此码进入……</view>
			</view>
		</view>
	</my-modal>
</template>

<script>
	export default{
		name: 'qr-modal',
		props: {
			signQrCode: { // 二维码信息
				type: String,
				default: ''
			},
			visible: { // 弹窗是否显示
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				time: '', // 当前时间
				isShow: false, // 弹窗是否显示
				avatarUrl: '', // 用户头像
				userName: '', // 用户姓名
				timeInterval:null
			}
		},
		onLoad() {
			const userInfo = this.$store.state.userInfo
			if (userInfo) {
				this.avatarUrl = userInfo.avatarUrl
				this.userName = userInfo.nickName
			}
		},
		watch: {
		    visible(val) {
				this.isShow = val
				// 显示时间
				if (val) {
					const date = new Date()
					this.time = `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
					this.timeInterval = setInterval(() => {
						const date = new Date()
						this.time = `${date.getFullYear()}年${date.getMonth()+1}月${date.getDate()}日${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`
					}, 1000)
				}
		    }
		},
		methods: {
			// 保存二维码图片
			saveQRCode() {
				uni.showLoading({
				  mask: true,
				  title: '请稍后...'
				})
				this.$refs.uQRCode.save({
					success: res => {
						console.log(res)
						uni.hideLoading()
						uni.showToast({
							title: res.msg
						})
					},
					fail: err => {
						uni.hideLoading()
						uni.showToast({
							icon: 'none',
						    title: err.errMsg
						})
					}
					
				})
			},
			// 关闭弹窗
			closeModal() {
				clearInterval(this.timeInterval)
				this.$emit('close')
			}
		}
	}
</script>

<style lang="scss" scoped>
	.code-modal-content {
		padding: 28rpx;
		.modal-image-box {
			-webkit-justify-content: center;
			justify-content: center;
			-webkit-align-items: center;
			align-items: center;
			.modal-content-image {
				width: 100rpx;
				height:100rpx;
			}
		}
		.modal-user-info {
			-webkit-justify-content: space-between;
			justify-content: space-between;
			margin-left: 30rpx;
			font-size: 24rpx;
		}
		.modal-qr-box {
			margin: 30rpx 0;
			justify-content: center;
			align-items: center;
			.modal-hint {
				margin-top: 30rpx;
				font-size: 24rpx;
			}
		}
	}
</style>
